package com.asiainfo.indb.control.db;

import com.asiainfo.indb.control.LogService;
import com.asiainfo.indb.control.db.pool.DbPoolFactory;
import com.asiainfo.indb.model.InDbGather;
import com.asiainfo.indb.view.TablePanel;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author zym
 * @date 2019-10-21 14:39
 */
public abstract class FileLineInDb {

    private InDbGather gather;
    private LogService log;

    /**
     * 分隔符
     */
    private String delimiter;

    /**
     * 表名
     */
    private String tableName;

    /**
     * 列
     */
    private String[] cols;

    private Connection connection;

    public FileLineInDb(InDbGather gather, LogService log) {
        this.gather = gather;
        this.log = log;

        // 分隔符
        this.delimiter = gather.get("SPLIT");
        // TODO 某些转义字符需要替换为本身
        this.delimiter = this.delimiter.replaceAll("|", "\\\\|");

        this.tableName = gather.get("TABLE_NAME");
        this.cols = gather.get("TABLE_COLS").split(TablePanel.COL_SPLIT);
    }

    /**
     * 主入口，每行数据入库
     *
     * @param line 一行数据
     * @return 返回错误数据，如果正确入库则返回Null
     */
    public String inDb(String line) {
        if (StringUtils.isNotBlank(line)) {
            String[] values = line.split(this.delimiter);
            if (values.length == this.cols.length) {
                // 入库
                insertDb(getInsertSQL(this.tableName, this.cols), values);
                log.deal(1);
            } else {
                debug("异常长度数据：" + line);
            }
        }

        return line;
    }

    /**
     * 停止入库
     */
    public abstract void endInDb();

    /**
     * 实际入库操作
     *
     * @param insertSQL 入库SQL
     * @param values    值
     */
    protected abstract void insertDb(String insertSQL, String[] values);

    /**
     * 获取连接
     *
     * @return 连接
     */
    protected Connection getConnection() {
        try {
            if (this.connection != null && !this.connection.isClosed()) {
                return this.connection;
            }

            this.connection = DbPoolFactory.getPool(gather).getConnection();
            return this.connection;
        } catch (SQLException e) {
            log.report("获取连接异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 日志输出
     *
     * @param msg 日志
     */
    protected void debug(String msg) {
        if (log != null && msg != null) {
            log.report(msg);
        }
    }

    /**
     * 获取入表的SQL，需要自己实现，是oracle的还是mysql的亦或其它数据库？
     *
     * @param tb   表名
     * @param cols 列
     * @return sql
     */
    protected String getInsertSQL(String tb, String[] cols) {
        return DbPoolFactory.getPool(gather).getDialect().getInsertSQL(tb, cols, isBatchInsert());
    }

    /**
     * 是否批量插入，默认是
     *
     * @return 是否
     */
    protected boolean isBatchInsert() {
        return true;
    }

}